package org.springblade.system.excel;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;

import java.lang.reflect.Field;
import java.util.Map;

public class ExcelSelectorLongConverter implements Converter<Long> {
	@Override
	public Class supportJavaTypeKey() {
		return Long.class;
	}

	@Override
	public CellDataTypeEnum supportExcelTypeKey() {
		return CellDataTypeEnum.STRING;
	}

	@Override
	public Long convertToJavaData(ReadCellData cellData, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
		String dictValue = cellData.getStringValue();
		Field field = excelContentProperty.getField();
		ExcelSelector annotation = field.getAnnotation(ExcelSelector.class);
		if (annotation != null) {
			String dictKeyValue = annotation.dictKeyValue();
			ExcelSelector.ValueType valueType = annotation.valueType();
			Map<String, Object> bizDict;
			if (valueType == ExcelSelector.ValueType.MAIN) {
				bizDict = ExcelSelectorCache.get(dictKeyValue);
			} else {
				dictKeyValue = dictKeyValue+ExcelSelectorCache.sub;
				bizDict = ExcelSelectorCache.get(dictKeyValue);
			}
			if (bizDict == null || bizDict.isEmpty()) {
				return null;
			}
			Map<String, String> value2Key = (Map<String, String>) bizDict.get(ExcelSelectorCache.value2key);
			String dictKey = value2Key.get(dictValue);
			return Long.parseLong(dictKey);

		}
		return Long.parseLong(dictValue);
	}

	@Override
	public WriteCellData convertToExcelData(Long dictKey, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
		Field field = excelContentProperty.getField();
		ExcelSelector annotation = field.getAnnotation(ExcelSelector.class);
		if (annotation != null) {
			String dictKeyValue = annotation.dictKeyValue();
			ExcelSelector.ValueType valueType = annotation.valueType();
			Map<String, Object> bizDict;
			if (valueType == ExcelSelector.ValueType.MAIN) {
				bizDict = ExcelSelectorCache.get(dictKeyValue);
			} else {
				dictKeyValue = dictKeyValue+ExcelSelectorCache.sub;
				bizDict = ExcelSelectorCache.get(dictKeyValue);
			}
			if (bizDict == null || bizDict.isEmpty()) {
				return new WriteCellData(String.valueOf(dictKey));
			}
			Map<String, String> key2Value = (Map<String, String>) bizDict.get(ExcelSelectorCache.key2value);
			String dictValue = key2Value.get(String.valueOf(dictKey));
			return new WriteCellData(dictValue);

		}
		return new WriteCellData(String.valueOf(dictKey));
	}
}
